<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/20
 * Time: 13:38
 */

namespace common\business\mdm;


use common\business\DbHandler;
use common\business\EhrHelper;
use common\helpers\StringUtil;
use common\models\kingdee\OrgAdmin;
use common\models\kingdee\OrgPosition;
use common\models\kingdee\Person;
use common\models\mdm\MdmDept;
use common\models\mdm\MdmEmployee;
use common\models\mdm\MdmPosition;
use common\result\ActionResult;
use yii\db\Exception;
use yii\db\Query;
use Yii;

class MdmEmployeeService extends DbHandler
{
    /**
     * @var string
     */
    protected $_department_number;
    public function setDepartmentNumber($department_number){
        $this->_department_number = $department_number;
    }

    /**
     * @param callback|null $writeBackHandler
     * @return ActionResult
     */
    public function sync($writeBackHandler = null){
        $totalResult = new ActionResult();
        $apiHandler = new MdmHandler();
        $apiHandler->setCrud(new MdmEmployeeCrud());

        $db = Person::getDb();

        if (!StringUtil::isNullOrWhiteSpace($this->_department_number)){
            $org = OrgAdmin::findOne([
                'FNUMBER' => $this->_department_number
            ]);

            $orgIdParams = [
                'fid' => $org->FID
            ];
            $cmd = $db->createCommand('SELECT t.fid FROM T_ORG_ADMIN t START WITH t.fid = :fid CONNECT BY t.fparentid = PRIOR fid', $orgIdParams);
//        $cmd->bindParam('fid', $orgId);
            try {
                $orgIdArr = $cmd->queryColumn();
            } catch (Exception $e) {
                return null;
            }
        }

        $query = (new Query())->from('T_BD_PERSON TBP')
            ->leftJoin('T_HR_PERSONPOSITION THPP', 'THPP.FPERSONID = TBP.FID')
            ->leftJoin('T_ORG_POSITION TOP', 'TOP.FID = THPP.FPRIMARYPOSITIONID')
            ->leftJoin('T_ORG_ADMIN TOA', 'TOA.FID = TOP.FADMINORGUNITID')
            ->leftJoin('T_HR_EMPLABORRELATION THELR', 'THELR.FPERSONID = TBP.FID')
            ->leftJoin('T_HR_BDEMPLOYEETYPE THBET', 'THBET.FID = THELR.FLABORRELATIONSTATEID')
            ->select([
                'PERSONNAME' => 'TBP.FNAME_L2',
                'PRESONCODE' => 'TBP.FNUMBER',
                'org_number' => 'TOA.FNUMBER',
                'position_number' => 'TOP.FNUMBER',
                'gender' => 'TBP.FGENDER',
                'BIRTHDATE' => 'to_char(TBP.FBIRTHDAY , \'yyyy-MM-dd hh:mm:ss\')',
                'PERSONID' => 'TBP.FIDCARDNO',
                'labor_relation_state' => 'THBET.FNAME_L2',
//                是否在职，在职=1,不在职=0,离职=2,离退休=3,返聘=4
                'in_service' => 'THBET.FINSERVICE',
                'STARTDATE' => 'to_char(TBP.FEFFDT, \'yyyy-MM-dd\')',//
            ]);

        if (!StringUtil::isNullOrWhiteSpace($this->_department_number)){
            $query->andFilterWhere([
                'in' , 'TOP.FADMINORGUNITID', $orgIdArr
            ]);
        }

        $query->orderBy([
            'TOP.FID' => SORT_ASC,
        ]);

        $totalCount = $query->count('*', $db);

        $offset = 0;
        $pageSize = 100;
        $count = $pageSize;

        while ($count >= $pageSize) {
            $all = $query->offset($offset)->limit($pageSize)->all($db);
            $count = count($all);
            $offset += $pageSize;
            foreach ($all as $employee){
                $ssMdmOrg = EhrHelper::findSsMdmOrgByNumber($employee['org_number']);
                if($ssMdmOrg){
                    $employee['SSORG'] = $ssMdmOrg->PK_MDM_ORG;
                }

                $mdmDept = MdmDept::findOne(['DEPARTMENTCODE' => $employee['org_number']]);
                if ($mdmDept){
                    $employee['PERSONDEPART'] = $mdmDept->PK_DEPARTMENT;
                }

                $mdmPosition = MdmPosition::findOne(['POSTCODE' => $employee['position_number']] );
                if ($mdmPosition){
                    $employee['PERSONPOST'] = $mdmPosition->PK_POST;
                }

                $newMdmEmployee = new MdmEmployee();
                $newMdmEmployee->setAttributes($employee);
                $newMdmEmployee->VVDEF1 = Yii::t('app', 'Id Card');
                $newMdmEmployee->PERSONSEX = EhrHelper::getGenderByIntValue($employee['gender']);
                $newMdmEmployee->ISNOTUSE = ($employee['in_service'] != 1);

                $mdmEmployeeInDb = MdmEmployee::findOne([
                    'PRESONCODE' => $newMdmEmployee->PRESONCODE,
                ]);

                if (!$mdmEmployeeInDb){
                    $totalResult->addSubResult($apiHandler->create($newMdmEmployee));
                }
                else {
                    $totalResult->addSubResult($apiHandler->update($newMdmEmployee, $mdmEmployeeInDb, [
                        'PERSONNAME', 'PRESONCODE', 'SSORG', 'BIRTHDATE', 'PERSONID',
                        'PK_DEF1', 'PERSONPOST', 'VVDEF1', 'PERSONSEX', 'ISNOTUSE'
                    ]));
                }
                if ($writeBackHandler){
                    $paramArr = [
                        'totalCount' => $totalCount,
                        'finishCount' => $totalResult->total_count,
                        'message' => $totalResult->message,
                    ];
                    call_user_func_array($writeBackHandler, $paramArr);
                }
            }
        }
        return $totalResult;
    }
}